var handleData = function(_val){
    console.log('Handle datatime:' , _val);
    var _vals = _val.split('T')
    console.log(_vals)

    var newDatatime =_vals[0] +' '+ _vals[1];

    console.log(newDatatime , 'newDatatime')

    var date = new Date(newDatatime.replace(/-/g, '/')).getTime();

    console.log(date)

    delete  _vals

    return date
}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/activity/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
			{ label: '活动名称', name: 'name', index: 'name', width: 80 }, 			
			{ label: '类型', name: 'type', index: 'type', width: 80 ,formatter: function(value, options, row){
                if(value === 2){
                    return '<span class="label label-primary">好友帮砍</span>';
                }
                if(value === 4){
                    return '<span class="label label-success">新品试吃</span>';
                }
                if(value === 3){
                    return '<span class="label label-warning">限时抢购</span>';
                }
                if(value === 5){
                    return '<span class="label label-warning">新人专享</span>';
                }
            }  },
			{ label: '开始时间', name: 'starttime', index: 'starttime', width: 80 }, 			
			{ label: '结束时间', name: 'endtime', index: 'endtime', width: 80 }, 			
			{ label: '是否开始', name: 'isopen', index: 'isopen', width: 80 ,formatter: function(value, options, row){
                if(value === 0){
                    return '<span class="label label-primary">未开始</span>';
                }
                if(value === 1){
                    return '<span class="label label-success">已开始</span>';
                }
                if(value === 2){
                    return '<span class="label label-warning">已结束</span>';
                }
            }
            },
            { label: '背景图', name: 'bannerurl', index: 'bannerurl', width: 80 },
			{ label: '说明', name: 'description', index: 'description', width: 80 }, 			
			{ label: '创建时间', name: 'createtime', index: 'createtime', width: 80 }, 			
			{ label: '创建人', name: 'createuser', index: 'createuser', width: 80 }, 			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{
            name:null
        },
		showList: true,
		title: null,
		activity: {
            bannerurl:null
        },
        sels: [
            {id:"2",typename:"好友帮砍"},
            {id:"4",typename:"新品试吃"},
            {id:"3",typename:"限时抢购"},
            {id:"5",typename:"新人专享"},
		],
        bannercache:""
	},
	methods: {
        changeImage: function(e) {
            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function(e) {
                // this.result 为图片
                THIS.upload(this.result)
            }
        },
        upload: function(data) {
            // 上传图片
            var THIS = this;
            if(this.$refs.file.files.length !== 0) {
                var image = new FormData()
                image.append('file', this.$refs.file.files[0])

                $.ajax({
                    url: '/liquor/uploadimage3',
                    data: image,
                    // headers: {
                    //     "Content-Type": "multipart/form-data"
                    // },
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function(result) {
                        console.info(result.address);
                        THIS.activity.bannerurl = result.address;
                        THIS.bannercache = result.address;
                    },
                    error: function(error) {
                        alert('图片上传失败!');
                    }
                })
            }
        },
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
            bannercache=null;
			vm.activity = {};
		},
        getCommodityList: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showDom = "commodityList"
            window.location.href = 'commodity2.html?id='+id
        },
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var url = vm.activity.id == null ? "sys/activity/save" : "sys/activity/update";
            vm.activity.starttime = handleData(vm.activity.starttimeOld)
            vm.activity.endtime = handleData(vm.activity.endtimeOld)

            $.ajax({
				type: "POST",
			    url: baseURL + url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.activity),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/activity/delete",
				    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "sys/activity/info/"+id, function(r){
                var time1 = r.activity.starttime
                var time2 = r.activity.endtime
                vm.activity = r.activity;
                vm.activity.starttimeOld = time1.replace(" ","T")
                vm.activity.endtimeOld = time2.replace(" ","T")
                vm.bannercache = r.activity.bannerurl
            });
		},
		reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'name': vm.q.name},
                page:page
            }).trigger("reloadGrid");
		}
	}
});